import router from './router'
import store from '@/store'
const whiteList = ['/login', '/404']
// 虚假进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
NProgress.configure({ showSpinner: false }) // 去掉进度条右上角的转圈
// 前置路由守卫
router.beforeEach(async(to, from, next) => {
  const token = store.getters.token
  NProgress.start()
  if (token) {
    if (!store.state.user.userInfo.userId) {
      const menus = await store.dispatch('user/getUserInfo')
      console.log(menus)
      // 第二种思路
      // console.log(store.state.user.userInfo.roles.menus)
      // console.log(asyncRoutes)
      // const selectedRoutes = asyncRoutes.filter(item => menus.includes(item.name))
      // console.log(selectedRoutes)
      const selectedRoutes = await store.dispatch('permissions/filterRoute', menus)
      console.log(selectedRoutes)
      // 路由对象就相当于后添加了一些动态的路由规则
      router.addRoutes(selectedRoutes)
    }

    if (to.path === '/login') {
      next('/')
    } else {
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
  NProgress.done()
})

// 后置路由守卫
router.afterEach(() => {
  NProgress.done()
})
